<?php

namespace App\Library\Logic;

use App\Library\Requests\Im\ImNewRequest;
use App\Library\Requests\Im\ImPageRequest;
use App\Models\ShopCustomerImModel;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\DB;

class ShopCustomerImLogic extends ShopCustomerImModel
{
    /**
     * 分页
     * @param ImPageRequest $request
     * @return array
     */
    public function paging(ImPageRequest $request): array
    {
        $builder = $this->newQuery()->where(function (Builder $builder) use ($request) {
            $builder->where(function (Builder $builder) use ($request) {
                $builder->where('send_user_id', USERID)->where('receive_user_id', $request->acceptId);
            })->orWhere(function (Builder $builder) use ($request) {
                $builder->where('send_user_id', $request->acceptId)->where('receive_user_id', USERID);
            });
        });
        if ($request->id > 0) $builder->where('ci_id', '<', $request->id);
        return paginate($builder->orderByDesc('ci_id')->paginate($request->limit, $this->columns()));
    }

    /**
     * 最新
     * @param ImNewRequest $request
     * @return Collection|array
     */
    public function new(ImNewRequest $request): Collection|array
    {
        return $this->newQuery()->where(function (Builder $builder) use ($request) {
            $builder->where(function (Builder $builder) use ($request) {
                $builder->where('send_user_id', USERID)->where('receive_user_id', $request->acceptId);
            })->orWhere(function (Builder $builder) use ($request) {
                $builder->where('send_user_id', $request->acceptId)->where('receive_user_id', USERID);
            });
        })->where('ci_id', '>', $request->id)->orderByDesc('ci_id')->get($this->columns());
    }

    private function columns(): array
    {
        return ['ci_id',
            'ci_content',
            'ci_content_img',
            'add_at',
            DB::raw('if(send_user_id=' . USERID . ',1,0) as my')
        ];
    }
}
